/* 
 * @name login.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
 */

var ReportCustomerDetials = {

    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;

        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Customer', name:'customer_id', width:280, sortable:true, align:'center', hide:false},
                {display:'Total Opening Balance', name:'open_bal', width:150, sortable:false, align:'center', hide:false},
                {display:'Total Undue', name : 'total_undue', width : 120, sortable : false, align: 'center', hide:false},
                {display:'Total Past Due', name : 'total_pastdue', width : 120, sortable : false, align: 'center', hide:false},
                {display:'Total Repayment', name : 'total_installment', width : 120, sortable : false, align: 'center', hide:false},
                {display:'Total Principal Balance', name:'balance', width:180, sortable:false, align:'center', hide:false},
                {display:'Total Interest', name:'interest', width:180, sortable:false, align:'center', hide:false},
                {display:'Total Balance', name:'total_balance', width:120, sortable:false, align:'center', hide:false}
            ],
            formFields:[
                {type:'buttom', name:'More Detail', bclass:'view', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Print', bclass:'print', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Export', bclass:'export', onpress:self.handleGridEvent},
                {separator:true},
                {type:'select', name:'Select Transaction Currency', id:'select_currency' ,bclass:'person', options:gbl_currency_opts , onchange:self.handleGridEvent}
            ],
            /*searchitems : [
             {display: 'Name', name : 'name', isdefault: true}
             ],*/
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:false,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300,
            onSubmit: self.addFormData
        });

        self.initDataTypeMenus();
    },

    handleGridEvent:function (com, grid, json) {
        if (com == 'More Detail') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                ReportCustomerDetials.view(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Print') {
            if (jLib.rowSelectedCheck(grid)) {
                ReportCustomerDetials.print_export_Details(jLib.getSelectedRowIds(grid),'print');
            }
        }
        else if (com == 'Export') {
            if (jLib.rowSelectedCheck(grid)) {
                ReportCustomerDetials.print_export_Details(jLib.getSelectedRowIds(grid),'export');
            }
        }
        else if (com == 'Select Transaction Currency') {
            ReportCustomerDetials.filterCustomers(json);
        }
    },

    filterCustomers:function(value){
        var self = this;
        self.objGrid.flexOptions({params: [{name:'currency',value:value}]}).flexReload();
        return false;
    },

    addFormData:function(){
        var self = this;
        var val = $("#select_currency").val();
        //self.objGrid.flexOptions({params: [{name:'customer_id',value:val}]});
        $('#flex').flexOptions({params: [{name:'currency',value:val}]});
        return true;
    },


    print_export_Details: function(row_ids,data_type){
        var data_ids = '';
        if (typeof row_ids != null) {
            for (var x in row_ids) {
                data_ids += '' + row_ids[x] + ','
            }
        }
        $("#print-export-form #data_type").val(data_type);
        $("#print-export-form #data_ids").val(data_ids);
        $("#print-export-form #pe_currency").val($("#select_currency").val());
        //$("#print-export-form #pe_customer_id").val($("#select_customer").val());
        window.open('', "PrintExportWindow", "menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        //document.getElementById('popUpform').submit();
        $("#print-export-form").submit();
    },

    /* print_export_Details: function(data_type){
     var dataUrl = $('#table-url').val();
     var currency = $("#select_currency").val();
     var url = dataUrl+'/'+currency+'/'+data_type;
     window.open(url,data_type,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
     },*/

    view:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];
        if(dataID == 'tl'){
            return;
        }
        var currency = $("#select_currency").val();
        var url = $('#load-user-url').val();
        var query = 'type=load&data-id=' + dataID+'&currency='+currency;
        $.post(url, query, function (response) {
            if (response.code === 0) {
                var dataObj = response.data;
                var cust_dt = dataObj['cutomer_sales'][dataID];
                //console.log(cust_dt);
                $('#customer-sales-detail-window #transaction_currency').html(currency);
                $('#customer-sales-detail-window #customer_in_transaction').html(cust_dt['info']['name']);

                $('table#customer-sales-detail_flex tbody').html('');

                $.each(cust_dt.sales,function(index, row){
                    var tr = $("<tr />");
                    tr.append($("<td />").html(row['purchased_date']));
                    tr.append($("<td />").html(row['invoice_number']));
                    tr.append($("<td />").html(row['vehicle_no']));
                    tr.append($("<td />").html(jLib.formatNumber(row['opening_bal'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['mth_inst'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['repayment'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['undue'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['pastdue'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['interest'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['principal_bal'],'money')));
                    tr.append($("<td />").html(jLib.formatNumber(row['total_bal'],'money')));

                    $('table#customer-sales-detail_flex tbody').append(tr);
                });


                var totals = dataObj['overall_totals'];

                var tr = $("<tr />");
                tr.append($("<td />").html(''));
                tr.append($("<td />").html(''));
                tr.append($("<td />").html('<strong>TOTAL</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_opening_bal'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_mth_inst'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_repayment'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_undue'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_pastdue'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_interest'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_principal_bal'],'money')+'</strong>'));
                tr.append($("<td />").html('<strong>'+jLib.formatNumber(totals['overall_total_bal'],'money')+'</strong>'));

                $('table#customer-sales-detail_flex tbody').append(tr);

                self.selected_row_id = dataID;

                $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'Customer Sales Information',
                    href:"#customer-sales-detail-window"
                });
            }
            /* When there are Errors */
            else if (response.code === 1) {
                /* Alert the user that the server response*/
                jLib.setFeedback(response.mesg, 'error_message', false);
            }
        }, 'json');
    },

    initDataTypeMenus:function(){
        var self = this;

        $("button.data-type-menu").live('click',function(){

            var currency = $("#select_currency").val();
            //var url = $('#load-user-url').val();
           // var query = 'type=load&data-id=' + dataID+'&currency='+currency;
            var action = $('#load-user-url').val();
            var data_type = $(this).attr('data-type');
            var url = action+'/'+self.selected_row_id+'/'+currency+'/'+data_type;

            window.open(url,data_type,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        });

    }
};

/* when the page is loaded */
$(document).ready(function() {
    ReportCustomerDetials.init();
});